define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        // 存储表格实例，方便全局访问
        table: null,
        
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/job_order/index' + location.search,
                    add_url: 'pt/job_order/add',
                    edit_url: 'pt/job/edit',
                    del_url: 'pt/job_order/del',
                    multi_url: 'pt/job_order/multi',
                    import_url: 'pt/job_order/import',
                    table: 'pt_job',
                }
            });

            // 初始化表格并存储到控制器属性
           var table = $("#table");

            // 获取工作细项配置并生成列
            function getJobDetailColumns() {
                var columns = [];
                var jobDetailConf = window.job_detail_conf || [];
                
                jobDetailConf.forEach(function(item) {
                    var title = item[0];
                    var code = item[1];
                    var fieldName = code + 'status';
                   
                   
                    columns.push({
                        field: code,
                        title: title,
                        operate: false,
                        width: 80,
                        formatter: function(value, row, index) {
                            var colorClass = row[code + 'color'];
              
                            
                            var buttonText = row[fieldName] || '未执行';
                            var jobId = row[code + 'job_id'];
                            var orderId = row.id;
                            
                            return '<button type="button" class="btn btn-xs btn-dialog ' + colorClass + '" ' +
                                   'data-area=\'["1000px", "800px"]\' data-shade=\'0.3\' data-title=\'工作详情\' ' +
                                   'data-url="pt/job_order/detail?job_id=' + jobId + '&order_id=' + orderId + '">' +
                                   buttonText + '</button>';
                        }
                    });
                });
                
                return columns;
            }

                    
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {field: 'order_name', title: __('人员名称'), operate: 'LIKE', width: 150},
                        {field: 'pt_grade', title: __('职称等级'), width: 80},
                        // 动态生成工作细项列
                        ...getJobDetailColumns(),
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter:Table.api.formatter.buttons,
                            buttons:[
                                {
                                    name: 'edit',
                                    text: '人员设置',
                                    title: '人员设置',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    extend:' data-area=\'["600px", "800px"]\' data-shade=\'0.3\'',
                                    icon: 'fa fa-edit',
                                    url: function(row){
                                        return 'pt/job_order/reassign?order_id=' + row.id;
                                    },
                                    visible: function (row) {
                                        return true;
                                    }
                                },
                           
                            ]}
                    ]
                ]
            });

            // 绑定表格事件
            Table.api.bindevent(table);
            
            

            // 添加导出功能
            $('.btn-export').on('click', function() {
                Toastr.info('功能开发中');
                return false;
            });
        },
        

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        reassign: function () {
            Controller.api.bindevent();
            // 兼容不同表单ID
            var $form = $('#reassign-form').length ? $('#reassign-form') : $('#edit-form');
            // 初始化一次
            Controller.checkHasUpdate($form);
            // 变更时更新
            $form.on('change', '.worker-select, .responsibility-select', function () {
                Controller.checkHasUpdate($form);
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        detail: function () {
            Controller.api.bindevent();
            
            // 初始化继续教育记录
            var jobTypeCode = $('input[name="job_type_code"]').val();
            if (parseInt(jobTypeCode, 10) === 1) {
                Controller.loadEducationRecords();
            }
            // 初始化订单ID相关处理
            Controller.initOrderIdHandlers();
            
            // 初始化表单提交处理
            Controller.initFormSubmitHandlers();
        },
        
        // 加载继续教育记录
        loadEducationRecords: function() {
            if (typeof Controller.initEducationRecordList !== 'function') {
                return;
            }
            
            // 先加载已有记录，再初始化（这样 recordIndex 可以正确设置）
            var $hiddenData = $('#education-records-data');
            var existingRecordCount = 0;
            if ($hiddenData.length) {
                try {
                    var educationRecordsData = JSON.parse($hiddenData.val());
                    if (educationRecordsData && educationRecordsData.length > 0) {
                        existingRecordCount = educationRecordsData.length;
                    }
                } catch(e) {
                    console.error('解析继续教育记录数据失败:', e);
                }
            }
            
            // 初始化列表管理（传入已有记录数量）
            Controller.initEducationRecordList(existingRecordCount);
            
            // 加载已有记录
            if ($hiddenData.length && existingRecordCount > 0) {
                Controller.renderEducationRecords(JSON.parse($hiddenData.val()));
            }
        },
        
        // 渲染继续教育记录
        renderEducationRecords: function(educationRecordsData) {
            if (!educationRecordsData || educationRecordsData.length === 0) {
                return;
            }
            
            try {
                var $fieldlist = $('.fieldlist[data-name="education_records"]');
                var $addButton = $('#btn_add_row_education_records').closest('dd');
                var template = $('#tpl_education_records').html();
                var recordIndex = 0;
                
                educationRecordsData.forEach(function(record) {
                    var html = template.replace(/__INDEX__/g, recordIndex);
                    var $newRow = $(html);
                    
                    // 填充数据
                    if (record.year) {
                        $newRow.find('input[name*="[year]"]').val(record.year);
                    }
                    if (record.total_class_hour !== undefined) {
                        $newRow.find('input[name*="[total_class_hour]"]').val(record.total_class_hour);
                    }
                    
                    // 插入到"添加记录"按钮之前
                    $newRow.insertBefore($addButton);
                    
                    // 初始化selectpage并设置值
                    Controller.initSelectPageValue($newRow, record);
                    
                    recordIndex++;
                });
            } catch(e) {
                console.error('渲染继续教育记录失败:', e);
            }
        },
        
        // 初始化selectpage的值
        initSelectPageValue: function($newRow, record) {
            if (!record.platform_id || !record.platform_name) {
                return;
            }
            
            var $selectpage = $newRow.find('.selectpage');
            if (!$selectpage.length) {
                return;
            }
            
            // 先设置selectpage的初始值
            $selectpage.attr('data-value', record.platform_id);
            $selectpage.val(record.platform_name);
            
            // 初始化 selectpage，并设置值
            setTimeout(function() {
                require(['selectpage'], function() {
                    // 如果已经初始化过，先销毁
                    if ($selectpage.data('selectPageObject')) {
                        try {
                            $selectpage.selectPage('destroy');
                        } catch(e) {
                            // 忽略错误
                        }
                    }
                    
                    // 初始化 selectpage
                    try {
                        var dataSource = $selectpage.attr('data-source');
                        if (dataSource && typeof Fast !== 'undefined' && Fast.api && Fast.api.fixurl) {
                            dataSource = Fast.api.fixurl(dataSource);
                            $selectpage.attr('data-source', dataSource);
                        }
                        
                        $selectpage.selectPage({
                            eAjaxSuccess: function (data) {
                                data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                                data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                                return data;
                            }
                        });
                        
                        // 初始化后设置值
                        Controller.setSelectPageValue($selectpage, $newRow, record.platform_id, record.platform_name);
                    } catch(e) {
                        console.error('selectpage 初始化失败:', e);
                    }
                });
            }, 150);
        },
        
        // 设置selectpage的值
        setSelectPageValue: function($selectpage, $newRow, platformId, platformName) {
            setTimeout(function() {
                var selectPageObj = $selectpage.data('selectPageObject');
                if (selectPageObj) {
                    // 方法1：通过selectPageObject设置
                    if (selectPageObj.elem && selectPageObj.elem.hidden) {
                        selectPageObj.elem.hidden.val(platformId);
                        $selectpage.val(platformName);
                        $selectpage.selectPageRefresh();
                    } else {
                        // 方法2：直接通过name属性找到隐藏字段
                        var hiddenName = $selectpage.attr('name');
                        var $hiddenInput = $newRow.find('input[type="hidden"][name="' + hiddenName + '"]');
                        if (!$hiddenInput.length) {
                            $hiddenInput = $('input[type="hidden"][name="' + hiddenName + '"]');
                        }
                        if ($hiddenInput.length) {
                            $hiddenInput.val(platformId);
                            $selectpage.val(platformName);
                            $selectpage.selectPageRefresh();
                        } else {
                            // 方法3：直接设置值并刷新
                            $selectpage.val(platformName);
                            $selectpage.data('value', platformId);
                            $selectpage.selectPageRefresh();
                        }
                    }
                } else {
                    // 如果selectPageObject还没准备好，再延迟一下
                    setTimeout(function() {
                        Controller.setSelectPageValue($selectpage, $newRow, platformId, platformName);
                    }, 200);
                }
            }, 300);
        },
        
        // 初始化订单ID相关处理
        initOrderIdHandlers: function() {
            var orderId = $('input[name="order_id"]').val();
            
            // 监听职位选择变化，确保 order_id 始终被传递
            $('select[name="row[position_id]"]').on('change', function() {
                var leaderSelect = $('select[name="row[leader_id]"]');
                if (!leaderSelect.length) return;
                var currentUrl = leaderSelect.attr('data-url') || '';
                var baseUrl = currentUrl ? currentUrl.split('?')[0] : 'pt/job_order/worker';
                // 更新 leader select 的 data-url，确保包含 order_id
                if (orderId) {
                    leaderSelect.attr('data-url', baseUrl + '?order_id=' + orderId);
                } else if (currentUrl && currentUrl.indexOf('?') > -1) {
                    // 没有 orderId 则还原为基础 URL
                    leaderSelect.attr('data-url', baseUrl);
                }
            });
            
            // 初始化时也设置一次 order_id
            if (orderId) {
                var leaderSelect = $('select[name="row[leader_id]"]');
                if (leaderSelect.length) {
                    var currentUrl = leaderSelect.attr('data-url') || '';
                    var baseUrl = currentUrl ? currentUrl.split('?')[0] : 'pt/job_order/worker';
                    leaderSelect.attr('data-url', baseUrl + '?order_id=' + orderId);
                }
            }
            
            // 监听position变化，更新隐藏字段
            $('select[name="row[position_id]"]').on('change', function() {
                var selectedText = $(this).find('option:selected').text();
                $('#c-position_name').val(selectedText);
            });
            
            // 监听人员选择变化，更新隐藏字段
            $('select[name="row[worker_id]"]').on('change', function() {
                var selectedText = $(this).find('option:selected').text();
                $('#c-worker_name').val(selectedText);
            });
        },
        
        // 初始化表单提交处理
        initFormSubmitHandlers: function() {
            // 提交统一回调
            var onSubmitSuccess = function(data, ret) {
                var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : '操作成功';
                if (typeof parent !== 'undefined' && parent.Toastr) {
                    parent.Toastr.success(msg);
                    parent.$(".btn-refresh").trigger("click");
                    if (window.name) {
                        var index = parent.Layer.getFrameIndex(window.name);
                        parent.Layer.close(index);
                    }
                } else {
                    Toastr.success(msg);
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                }
                return false;
            };
            
            var onSubmitError = function(data, ret) {
                var errorMsg = ret && ret.msg ? ret.msg : '操作失败，请稍后重试';
                if (typeof parent !== 'undefined' && parent.Toastr) {
                    parent.Toastr.error(errorMsg);
                } else {
                    Toastr.error(errorMsg);
                }
            };
            
            // 处理操作按钮点击
            $('.btn-action').on('click', function(e) {
                e.preventDefault();
                
                // 检查人员是否选择了
                var actionValue = $(this).val();
                if(!$('#c-worker_name').val() && actionValue == 'save'){
                    Toastr.error('请选择人员');
                    return false;
                }
                
                $('#form-action').val(actionValue);
                
                var form = $('#job-form');
                if (actionValue === 'save') {
                    // 提交时需要校验
                    form.trigger('submit');
                } else {
                    // 撤回需要二次确认
                    if (actionValue === 'back') {
                        Layer.confirm('确认撤回该工作吗？', {icon: 3, title: '提示'}, function(index){
                            Layer.close(index);
                            Form.api.submit(form, onSubmitSuccess, onSubmitError);
                        });
                        return false;
                    }
                    // 其他操作不需要校验，直接提交
                    Form.api.submit(form, onSubmitSuccess, onSubmitError);
                }
                
                return false;
            });
        },
        
        // 科研论文列表管理
        initResearchPaperList: function() {
            var paperIndex = 0;
            
            // 添加论文
            $('#btn_add_row_research_papers').on('click', function() {
                var template = $('#tpl_research_papers').html();
                var html = template.replace(/__INDEX__/g, paperIndex);
                $('.fieldlist[data-name="research_papers"]').append(html);
                paperIndex++;
            });
            
            // 删除论文
            $(document).on('click', '.btn-remove', function() {
                $(this).closest('dd').remove();
            });
        },
        
        // 继续教育记录列表管理
        initEducationRecordList: function(startIndex) {
            var recordIndex = startIndex || 0;
            var $form = $('form[role=form]');
            
            // 初始化 selectpage 的辅助函数
            var initSelectPage = function($element) {
                if (!$element || !$element.length) return;
                var $selectpage = $element.find('.selectpage');
                if (!$selectpage.length) return;
                
                require(['selectpage'], function(SelectPage) {
                    $selectpage.each(function() {
                        var $this = $(this);
                        // 如果已经初始化过，先销毁再重新初始化
                        if ($this.data('selectPageObject')) {
                            try {
                                $this.selectPage('destroy');
                            } catch(e) {
                                console.warn('销毁 selectpage 失败:', e);
                            }
                        }
                        // 初始化 selectpage
                        try {
                            var dataSource = $this.attr('data-source');
                            // 修复 URL（如果需要）
                            if (dataSource && typeof Fast !== 'undefined' && Fast.api && Fast.api.fixurl) {
                                dataSource = Fast.api.fixurl(dataSource);
                                $this.attr('data-source', dataSource);
                            }
                            
                            $this.selectPage({
                                eAjaxSuccess: function (data) {
                                    data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                                    data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                                    return data;
                                }
                            });
                           // console.log('selectpage 初始化成功:', dataSource);
                        } catch(e) {
                            console.error('selectpage 初始化失败:', e, $this);
                        }
                    });
                });
            };
            
            // 添加记录 - 阻止FastAdmin fieldlist组件的自动处理，避免重复添加
            $('#btn_add_row_education_records').off('click').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation(); // 阻止事件冒泡，防止FastAdmin fieldlist组件处理
                
                var template = $('#tpl_education_records').html();
                var html = template.replace(/__INDEX__/g, recordIndex);
                var $newRow = $(html);
                var $addButton = $(this).closest('dd');
                
                // 插入到"添加记录"按钮之前，而不是之后
                $newRow.insertBefore($addButton);
                recordIndex++;
                
                // 初始化新添加的 selectpage - 延迟确保 DOM 已插入
                setTimeout(function() {
                    initSelectPage($newRow);
                }, 100);
                
                return false;
            });
            
            // 删除记录
            $(document).on('click', '.fieldlist[data-name="education_records"] .btn-remove', function() {
                $(this).closest('dd').remove();
            });
        },
        checkHasUpdate: function(form) {
            var $form = form || ($('#reassign-form').length ? $('#reassign-form') : $('#edit-form'));
            var $hasUpdate = $form.find('input[name="has_update"]');
            var updated = false;
            $form.find('.worker-select').each(function () {
                var $select = $(this);
                if ($select.is(':disabled')) {
                    return true; // continue
                }
                var original = String($select.data('original') || '');
                var current = String($select.val() || '');
                if (original !== current) {
                    updated = true;
                    return false; // break
                }
            });
            if (!updated) {
                $form.find('.responsibility-select').each(function () {
                    var $select = $(this);
                    if ($select.is(':disabled')) {
                        return true;
                    }
                    var original = String($select.data('original') || '0');
                    var current = String($select.val() || '0');
                    if (original !== current) {
                        updated = true;
                        return false;
                    }
                });
            }
            $hasUpdate.val(updated ? '1' : '0');
        }
    };
    return Controller;
});